﻿using UnityEngine;
using UnityEngine.UI;

namespace Core
{
    [DisallowMultipleComponent]
    public abstract class BasePanel : GameMono
    {
        [SerializeField]
        internal PanelStyleType panelStyle = PanelStyleType.Cover;
        [SerializeField]
        internal PanelLayerType panelLayer = PanelLayerType.Center;
        [SerializeField]
        internal bool isDefaultBackageground;

        internal PanelState panelState;
        internal int sortingLayer;

        internal string panelPath;
        internal Canvas canvas;

        private void Start()
        {
            var canvas = GetComponent<Canvas>();
            if (canvas == null)
            {
                canvas = gameObject.AddComponent<Canvas>();
                canvas.vertexColorAlwaysGammaSpace = true;
            }

            var gr = GetComponent<GraphicRaycaster>();
            if (gr == null)
                gr = gameObject.AddComponent<GraphicRaycaster>();

            canvas.overrideSorting = true;
            canvas.sortingOrder = sortingLayer;
        }

        internal void _OnInit(object data)
        {
            OnInit(data);
        }

        internal async ETTask _OnInitAsync(object data)
        {
            await OnInitAsync(data);
        }

        internal void _Freeze()
        {
            OnFreeze();
        }

        internal void _UnFreeze()
        {
            OnUnfreeze();
        }

        internal void _Close()
        {
            OnClose();
        }

        public bool IsHaveType(PanelStyleType styleType)
        {
            return ((int)styleType & (int)panelStyle) > 0;
        }

        public void Close(bool clearLayer = false)
        {
            if (clearLayer)
                new CloseLayerPanels() { layer = panelLayer }.Publish();
            else
                new ClosePanel() { path = panelPath }.Publish();
        }

        /// <summary>
        /// 页面初始化
        /// </summary>
        protected virtual void OnInit(object data) { }

        /// <summary>
        /// 页面初始化异步
        /// </summary>
        protected virtual async ETTask OnInitAsync(object data)
        {
            await ETTask.CompletedTask;
        }

        /// <summary>
        /// 页面上面打开其他页面时，此页面将被冻结
        /// </summary>
        protected virtual void OnFreeze() { }

        /// <summary>
        /// 页面上面的其他页面关闭返回到此页面时，此页面解冻
        /// </summary>
        protected virtual void OnUnfreeze() { }

        /// <summary>
        /// 页面关闭时
        /// </summary>
        protected virtual void OnClose() { }
    }

    public enum PanelStyleType
    {
        None = 0,
        Cover = 1 << 0,
    }
}


